<template>
  <div class="app-container">
    <fomCom :tableName='"projectSchedule"' @addFun='addFun' @tableGet='get'></fomCom>
    <div ref="gantt" class="left-container"/>
  </div>
</template>
<script>
  import gantt from 'dhtmlx-gantt'  // 引入模块
  import fomCom from '@/components/fomCom'  // 引入模块
  import 'dhtmlx-gantt/codebase/skins/dhtmlxgantt_terrace.css' //皮肤

  export default {
    name: 'gantt',
    components:{
      fomCom
    },
    data() {
      return {
        tasks: {
          data: [
            {
              id: 1,
              text: '计划时间',
              start_date: '2020-04-08',
              duration: 10,
              open: true, //默认打开，
              toolTipsTxt: 'xxxxxxxxxxxxxxxxx'
            }
          ]
        },
        objectId:'',
        tuName:'初始表格',
      }
    },
    mounted() {
      // this.initData()
      this.get()
    },
    created(){
    },
    methods: {
      get(value){
        console.log(value)
        let pageObj = {
          page:1,
          pageSize:1000,
          openid:this.$store.getters.openid
        }
        if (value) {
          pageObj.objectId = value
        }
        this.$Leancloud.dataRequest.getPage(pageObj,'projectSchedule').then((res)=> {
          if (res.list[0]) {
            this.objectId = res.list[0].id
            console.log('查询到的数据',JSON.parse(res.list[0].attributes.listContent))
            // ---- 下拉选择 -----
            // if (!value) {
            //   let optionsList = []
            //   res.list.forEach(element => {
            //     optionsList.push({
            //       value: element.id,
            //       label: element.attributes.name
            //     })
            //   });
            //   this.options[0].options = optionsList
            //   this.optionValue = optionsList[0].value
            // }
            // ---- 下拉选择 -----
            this.tasks.data = JSON.parse(res.list[0].attributes.listContent) 
            this.initData()
            // this.showData(res.list[0].attributes.content)
          } else {
            // this.$message('没有查到相关数据');
            console.log('没有查到相关数据',dataObj)
            this.addFun('初始表单',JSON.stringify(this.tasks.data))
            setTimeout(() => {
              this.get()
            }, 2000);
          }
        })
      },
      updateData(){
        if (this.objectId) {
          const taskCount = gantt.getTaskCount();
          let taskData = [];
          let openTask = [];
          for(let i = 0; i < taskCount; i++){
            let taskOne = {}
            const obj = gantt.getTaskByIndex(i);
            //打开状态继续打开
            if(obj.$open==true){
              openTask.push(obj.id)
            }
            //整理数据格式
            taskOne = obj;
            if(obj.parent){
              taskOne.parent = obj.parent;
            }
            taskData.push(taskOne);
          }
          console.log('初始表格',taskData)
          this.tasks.data = taskData

          this.$Leancloud.dataRequest.update(this.objectId,{
            listContent:JSON.stringify(this.tasks.data),
            openid:this.$store.getters.openid
          },'projectSchedule',this)
        }else{
          this.get()
        }
      },
      //开始时间-结束时间参数
      DateDifference: function(strDateStart, strDateEnd) {
        var begintime_ms = Date.parse(new Date(strDateStart.replace(/-/g, '/'))) //begintime 为开始时间
        var endtime_ms = Date.parse(new Date(strDateEnd.replace(/-/g, '/')))   // endtime 为结束时间
        var date3 = endtime_ms - begintime_ms //时间差的毫秒数
        var days = Math.floor(date3 / (24 * 3600 * 1000))
        return days
      },
      addFun(name,data){
        data = data?data:JSON.stringify([{
              id: 1,
              text: name,
              start_date: new Date(),
              duration: 10,
              open: true, //默认打开，
        }])
        
          let dataObj = {
            name:name || '初始表格',
            listContent:data,
            openid:this.$store.getters.openid
          }
          // 初始化 数据
          this.$Leancloud.dataRequest.push(dataObj,'projectSchedule',this).then(res=>{
            this.get(res.id)
          })
      },
      initData: function() {
        //清空数据
        gantt.clearAll();
          /*
          * 冒烟：fcca02    单元：fec0dc     回归：62ddd4   阶段：d1a6ff
          * */
          //设置图表区域的日期坐标最大值 var date = new Date(dateString.replace(/-/,"/"))
          //  gantt.config.start_date = new Date("2020-04-08".replace(/-/,"/")) ;
          //gantt.config.end_date = new Date("2020-04-18".replace(/-/,"/")) ; //结束时间需要+1天

          //自适应甘特图的尺寸大小, 使得在不出现滚动条的情况下, 显示全部任务
          // gantt.config.autosize = true
          //只读模式
          // gantt.config.readonly = true
          //是否显示左侧树表格
          // gantt.config.show_grid = true
          //表格列设置
          gantt.config.columns = [
            { name: 'text', label: '阶段名字', tree: true, width: '120' },
            {
              name: 'duration', label: '时长', align: 'center', template: function(obj) {
                return obj.duration + '天'
              }
            },
            // {name:"start_date", label:"开始时间", align: "center" },
            // {name:"end_date",   label:"结束时间",   align: "center" },
            {name: "add", label: "" },
          ]

          //弹出层
          gantt.config.lightbox.sections = [
              {name:"text", height:70, map_to:"text", type:"textarea",focus:true,width:200},                                                                     
              {name:"time", height: 70, map_to:"auto", type:"time", time_format: ["%Y", "%m", "%d"]},
              {name:"color", height:30, map_to:"color", type:"select", options: [ 
                {key:"#3db9d3", label: "普通"},
                {key:"#33cc33", label: "完成"},                                               
                {key:"#FF8247", label: "急"},                                             
                {key:"#ff6633", label: "紧急"}                                                 
              ]},
              {name:"status", height:30, map_to:"status", type:"select", options: [ 
                {key:"普通", label: "普通"},
                {key:"完成", label: "完成"},                                               
                {key:"急", label: "急"},                                             
                {key:"紧急", label: "紧急"}                                                 
              ]},
              {name:"toolTipsTxt", height:70, map_to:"toolTipsTxt", type:"textarea"}
          ];

          //时间轴图表中，如果不设置，只有行边框，区分上下的任务，设置之后带有列的边框，整个时间轴变成格子状。
          gantt.config.show_task_cells = true

          //汉化
          gantt.locale={
            date: {
                month_full: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
                month_short: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
                day_full: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
                day_short: ["日", "一", "二", "三", "四", "五", "六"]
            },
            labels: {
              dhx_cal_today_button: "今天",
              day_tab: "日",
              week_tab: "周",
              month_tab: "月",
              new_event: "新建日程",
              icon_save: "保存",
              icon_cancel: "关闭",
              icon_details: "详细",
              icon_edit: "编辑",
              icon_delete: "删除",
              confirm_closing: "请确认是否撤销修改!", //Your changes will be lost, are your sure?
              confirm_deleting: "是否删除计划?",
              section_description: "描述:",
              section_time: "时间范围:",
              section_type: "类型",
              section_text: "计划名称:",
              section_color: "颜色:",
              section_status: "状态:",
              section_toolTipsTxt: "说明:",
              /* grid columns */

              column_text: "计划名称",
              column_start_date: "开始时间",
              column_duration: "持续时间",
              column_add: "",

              /* link confirmation */

              link: "关联",
              confirm_link_deleting: "将被删除",
              link_start: " (开始)",
              link_end: " (结束)",

              type_task: "任务",
              type_project: "项目",
              type_milestone: "里程碑",

              minutes: "分钟",
              hours: "小时",
              days: "天",
              weeks: "周",
              months: "月",
              years: "年"
            }
          }

          //设置x轴日期
          gantt.config.scale_unit = 'day'
          gantt.config.step = 1
          gantt.config.date_scale = '星期' + '%D'

          //当task的长度改变时，自动调整图表坐标轴区间用于适配task的长度
          gantt.config.fit_tasks = true
          // 在时间线上增加一行显示星期
          gantt.config.subscales = [
            //{unit:"day",  step:1, date:"星期"+"%D" },
            { unit: 'day', step: 1, date: '%M' + '%d' + '日' }
          ]
          //时间轴图表中，任务条形图的高度
          gantt.config.task_height = 28
          //时间轴图表中，甘特图的高度
          gantt.config.row_height = 36
          //从后端过来的数据格式化
          gantt.config.xml_date = '%Y-%m-%d'

          //任务条显示内容
          gantt.templates.task_text = function(start, end, task) {
            return task.text + '(' + task.duration + '天)' + ( task.status?" 状态：" + task.status : "" ) 
          }
          // gantt.templates.task_class = function(start, end, task){return "xx";};
          //悬浮
          gantt.templates.tooltip_text = function(start, end, task) {
            // zhuangTai
            return "<b>任务名称:</b> "+task.text+"<br/><b>时长:</b> " + task.duration+"<br/><b>说明:</b>" +task.toolTipsTxt
            +"<br/><b>状态:</b>" +(task.status || '' )
            +"<br/><b>进度:</b>" +(parseInt(task.progress * 100) + `%`  || '' )
            ;
            // progress
            // return '<span style=\'font-size: 14px\'>' + task.toolTipsTxt + '</span>'
          }
          gantt.plugins({
              // 拖动时间线
              // 允许通过鼠标拖动滚动时间线视图。
              drag_timeline: true,
              // 高级拖放
              // 提供通过拖放创建和选择任务的可能性。 
              click_drag: true,
              // 工具提示
              // 可以为用户添加额外的信息，而不会让文本溢出屏幕。
              tooltip: true,
              // 垂直标记
              // 突出显示某些日期或日期范围。
              marker: true,
              // 取消
              // 允许您撤消/重做所做的更改。
              undo: true
          });

          gantt.templates.scale_cell_class = function(date) {
            /*if(date.getDay()== 0 || date.getDay()== 6){
              return "weekend";
            }*/
            return 'weekend'
          }
          //任务栏周末亮色
          // gantt.templates.task_cell_class = function(item,date){
          //   if(date.getDay()== 0 || date.getDay()== 6){
          //     return "weekend";
          //   }
          // };
          //任务条上的文字大小 以及取消border自带样式
          gantt.templates.task_class = function(start, end, item) {
            return item.$level == 0 ? 'firstLevelTask' : 'secondLevelTask'
          }

          //添加后触发
          gantt.attachEvent("onAfterTaskAdd", (id,item)=>{
            var tasksStore = gantt.getDatastore("task");
            console.log("添加后触发",this.tasks.data,tasksStore,id,item);
            this.updateData();
          });
          //移动进度后触发
          gantt.attachEvent("onAfterTaskDrag", (id, mode, e)=>{
            console.log("移动进度后触发");
            this.updateData();
          });
          //移动任务后触发
          gantt.attachEvent("onAfterTaskMove", (id, parent, tindex)=>{
            console.log("移动任务后触发");
            this.updateData();
          });
          //删除任务后触发
          gantt.attachEvent("onAfterTaskDelete", (id,item)=>{
            console.log("删除任务后触发");
            this.updateData();
          });
          //修改任务后触发
          gantt.attachEvent("onAfterTaskUpdate", (id,item)=>{
            console.log("修改任务后触发");
            this.updateData();
          })
          // 初始化
          gantt.init(this.$refs.gantt)
          // 数据解析
          console.log('数据解析',this.tasks)
          gantt.parse(this.tasks)
          
          gantt.addMarker({
              start_date: new Date(),
              css: 'today',
              text: '今日',
          });
          // gantt.addMarker({
          //     start_date: new Date('2020-04-10'),
          //     css: 'projectStartDate',
          //     text: '结束时间',
          // });
      }
    }
  }
</script>

<style lang="scss">
  .projectStartDate, .projectEndDate {
    background: #00bcd4;
  }
  .gantt_cal_light_wide .gantt_section_time{
    height: 30px!important;
  }
</style>
<style lang="scss" scoped>
  .firstLevelTask {
    border: none;
    .gantt_task_content{
      // font-weight: bold;
      font-size: 13px;
    }
  }

  .secondLevelTask {
    border: none;
  }

  .thirdLevelTask {
    border: 2px solid #da645d;
    color: #da645d;
    background: #da645d;
  }

  .milestone-default {
    border: none;
    background: rgba(0, 0, 0, 0.45);
  }

  .milestone-unfinished {
    border: none;
    background: #5692f0;
  }

  .milestone-finished {
    border: none;
    background: #84bd54;
  }

  .milestone-canceled {
    border: none;
    background: #da645d;
  }

  html, body {
    margin: 0px;
    padding: 0px;
    height: 100%;
    overflow: hidden;
  }

  .container {
    height: 900px;
    .left-container {
      height: 100%;
    }
  }

  .left-container {
    height: 600px;
  }

  .gantt_scale_line {
    border-top: 0;
  }

  .weekend {
    //background:#f4f7f4!important;
    color: #000000 !important;
  }

  .gantt_selected .weekend {
    background: #f7eb91 !important;;
  }

  .gantt_task_content {
    text-align: left;
    padding-left: 10px;
  }

  //上面任务条样式
  .gantt_task_scale {
    height: 45px !important;
  }

  .gantt_task .gantt_task_scale .gantt_scale_cell {
    line-height: 30px !important;
    height: 28px !important;
  }
</style>